package com.ppp.poi.service;

import com.ppp.poi.bean.base.BaseService;
import com.ppp.poi.bean.entity.Region;
import com.ppp.poi.bean.result.DistrictResult;
import com.ppp.poi.common.AppConstant;
import com.ppp.poi.dao.RegionDao;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * @author Wu Jin
 * @create 2020-02-04
 */
@Service
public class RegionsService extends BaseService<Region, RegionDao> {

  @Autowired
  private RegionDao regionDao;

  @Autowired
  private HttpService httpService;

  public List<Region> getByParentId() {
    List<Region> regions = dao.selectAll();
    List<Region> collect = regions.stream().filter(d -> "province".equalsIgnoreCase(d.getLevel())).collect(Collectors.toList());
    setChildren(collect, regions);
    return collect;
  }

  public void setChildren(List<Region> r, List<Region> regions) {
    if (CollectionUtils.isEmpty(r)) {
      return;
    }
    r.stream().forEach(d->{
      List<Region> collect = regions.stream().filter(o -> o.getParentId().equals(d.getId())).collect(Collectors.toList());
      d.setDistricts(collect);
      setChildren(collect, regions);
    });
  }

  @Transactional(rollbackFor = Exception.class)
  public void search() {
    String formatUrl = String.format(AppConstant.DISTRICT_URL, "787f1d270b86c546795c1dd7b40d0cf0", "中华人民共和国");
    DistrictResult districtResult = httpService.doGetForPojo(formatUrl, DistrictResult.class);
    List<Region> tmp = districtResult.getDistricts();
    insert(tmp, 0);
  }

  public void insert(List<Region> list, int pid) {
    if (CollectionUtils.isEmpty(list)) {
      return;
    }

    for (Region d : list) {
      d.setParentId(pid);
      if (!(d.getCitycode() instanceof String)) {
        d.setCitycode("");
      }
      int i = insert(d);
      insert(d.getDistricts(), d.getId());
    }

  }

}
